#include <iostream>      // 输入输出 (std::cout)
#include <thread>        // 线程管理 (std::thread)
#include <mutex>         // 互斥锁 (std::mutex, std::lock_guard)
#include <queue>         // 消息队列 (std::queue)
#include <condition_variable> // 条件变量 (std::condition_variable)
#include <any>           // 多类型消息支持 (std::any)
#include <chrono>        // 时间处理 (std::chrono::seconds)
class Actor
{
public:
    Actor() : running_(false) {}
    virtual ~Actor() { stop(); }

    void start()
    {
        running_ = true;
        thread_ = std::thread(&Actor::run, this);
    }

    void stop()
    {
        running_ = false;
        if (thread_.joinable())
            thread_.join();
    }

    template <typename T>
    void send(T &&message)
    {
        {
            std::lock_guard<std::mutex> lock(queue_mutex_);
            message_queue_.push(std::forward<T>(message));
        }
        condition_.notify_one();
    }

protected:
    virtual void process_message(const std::any &msg) = 0;

private:
    void run()
    {
        while (running_)
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            condition_.wait(lock, [this]
                            { return !message_queue_.empty() || !running_; });

            while (!message_queue_.empty())
            {
                auto msg = message_queue_.front();
                message_queue_.pop();
                lock.unlock();
                process_message(msg);
                lock.lock();
            }
        }
    }

    std::thread thread_;
    std::queue<std::any> message_queue_;
    std::mutex queue_mutex_;
    std::condition_variable condition_;
    bool running_;
};

class PrinterActor : public Actor
{
protected:
    void process_message(const std::any &msg) override
    {
        if (msg.type() == typeid(std::string))
        {
            std::cout << "Received: "
                      << std::any_cast<std::string>(msg)
                      << std::endl;
        }
        else if (msg.type() == typeid(int))
        {
            std::cout << "Received number: "
                      << std::any_cast<int>(msg)
                      << std::endl;
        }
    }
};

int main()
{
    PrinterActor actor1, actor2;

    actor1.start();
    actor2.start();

    actor1.send(std::string("Hello from Actor1"));
    actor2.send(42);
    actor2.send(std::string("Message to Actor2"));

    std::this_thread::sleep_for(std::chrono::seconds(1));

    actor1.stop();
    actor2.stop();

    return 0;
}